package com.example.hoasbackend.common;//import com.okancha.mapper.KcTeaRoomConsumeRecordDAOMapper;
//import com.okancha.po.KcTeaRoomConsumeRecord;
//import org.apache.commons.lang.StringUtils;
import com.example.hoasbackend.common.utls.RedisUtil;
import com.example.hoasbackend.service.IndentOperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 主要作用就是:接收过期的redis消息,获取到key,key就是订单号,然后去更新订单号的状态(说明一下:用户5分钟不支付的话取消用户的订单)
 */
@Transactional
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private IndentOperationService indentOperationService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired
    RedisUtil redisUtil;
    @Override
    public void onMessage(Message message, byte[] pattern) {

        long indentBatchId= Long.parseLong(message.toString());
        String thisState=redisUtil.get(indentBatchId+":state");
        long operationType;
        if(thisState.equals(IndentState.CREATED)){
            operationType=IndentOperationType.CANCEL;
        }else{
            operationType=IndentOperationType.REDIS_TIMEOUT;
        }

        indentOperationService.redisKeyExpirationSolution(
                indentBatchId,thisState,IndentState.nextState(thisState,operationType)
        );


        /*
       关于redis数据库的设计
       ${batchId} null专门用来expire
       ${batchId}:LIST ${indentIdList}可能不需要，看情况吧
       ${batchId}:CHECK_IN_TIME  ${DATESTRING}
       ${batchId}:CHECK_IN_TIME  ${DATESTRING}
       ${batchId}:STATE  ${statestring}
         */
//        if (!(orderCode == null || orderCode.equals(""))) {
//
//            // 去数据库把订单状态改成过期,这里是我们的业务逻辑
//            KcTeaRoomConsumeRecord kcTeaRoomConsumeRecord = new KcTeaRoomConsumeRecord();
//            kcTeaRoomConsumeRecord.setOrderStatus(5); // 5表示订单状态是过期
//            kcTeaRoomConsumeRecord.setOrderCode(orderCode);
//            kcTeaRoomConsumeRecordDAOMapper.updateKcTeaRoomConsumeRecordByCondition(kcTeaRoomConsumeRecord);
//        }

//        System.out.println("过期的订单号是: " + orderCode);

    }
}
